package com.base.cn.platform.os.controller.qa.question;

import com.base.cn.platform.os.common.constants.ConfigName;
import com.base.cn.platform.os.common.controller.BaseController;
import com.base.cn.platform.os.common.mybatis.Pagination;
import com.base.cn.platform.os.common.utils.DataUtil;
import com.base.cn.platform.os.common.utils.ObjectUtils;
import com.base.cn.platform.os.common.utils.StringUtils;
import com.base.cn.platform.os.common.utils.action.ActionKey;
import com.base.cn.platform.os.common.utils.result.ResultUtil;
import com.base.cn.platform.os.entity.course.catalog.CourseCatalog;
import com.base.cn.platform.os.entity.course.cou.Course;
import com.base.cn.platform.os.entity.manage.config.SysConfig;
import com.base.cn.platform.os.entity.qa.count.QaSumCount;
import com.base.cn.platform.os.entity.qa.question.QaQuestion;
import com.base.cn.platform.os.entity.qa.question.QuestionCondition;
import com.base.cn.platform.os.service.manage.config.SysConfigService;
import com.base.cn.platform.os.service.manage.user.integral.CusUserIntegralService;
import com.base.cn.platform.os.service.qa.question.QaQuestionBiz;
import com.github.pagehelper.PageInfo;
import com.google.gson.reflect.TypeToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.*;

/**
 * 问答问题Controller
 *
 * @author LIZHIPENG
 * @since 2018/4/12
 */
@RestController
@RequestMapping("/course")
public class QaQuestionController extends BaseController {

    @Autowired
    private QaQuestionBiz questionBiz;
    @Autowired
    private SysConfigService sysConfigService;
    @Autowired
    private CusUserIntegralService cusUserIntegralService;

    /**
     * 多条件查询问答
     * @param condition 查询条件
     * @param qaTypeData 是否设置问答类型数据
     * @param teacherData 是否设置问答老师数据
     * @param createUserData 是否设置创建的用户数据
     * @param qaAddData 是否设置追问数据
     * @param attendData 是否设置围观数据
     * @param tagData 是否设置标签数据
     * @param teacherPriceData 是否设置老师分成数据
     * @return  List<QaQuestion>
     */
    @RequestMapping("/findQuestionList")
    public List<QaQuestion> findQuestionList(@RequestBody QuestionCondition condition,
                                             @RequestParam("qaTypeData") boolean qaTypeData,
                                             @RequestParam("teacherData") boolean teacherData,
                                             @RequestParam("createUserData") boolean createUserData,
                                             @RequestParam("qaAddData") boolean qaAddData,
                                             @RequestParam("attendData") boolean attendData,
                                             @RequestParam("tagData") boolean tagData,
                                             @RequestParam("teacherPriceData") boolean teacherPriceData){
        return questionBiz.findQuestionList(condition,qaTypeData,teacherData,createUserData,qaAddData,attendData,tagData,teacherPriceData);
    }

    /**
     * 查询问题数量
     * @param condition 查询条件
     * @return 问题数量
     */
    @RequestMapping("/questionCount")
    public BigDecimal questionCount(@RequestBody QuestionCondition condition){
        return questionBiz.questionCount(condition);
    }

    /**
     * 分页查询问题列表
     * @param currentPage 页码
     * @param condition 条件
     * @param userId 用户ID
     * @param qaTypeData 是否设置问答分类数据
     * @param teacherData 是否设置讲师数据
     * @param createUserData 是否设置创建人数据
     * @return PageInfo<QaQuestion>
     */
    @RequestMapping("/queryQuestionListPage")
    public PageInfo<QaQuestion> queryQuestionListPage(@RequestParam(value = "currentPage", required = false, defaultValue = "1") int currentPage,
                                                      @RequestParam(value = "pageSize", required = false, defaultValue = "10") int pageSize,
                                                      @RequestBody QuestionCondition condition,
                                                      @RequestParam(value = "userId", required = false, defaultValue = "0") BigDecimal userId,
                                                      @RequestParam("qaTypeData")boolean qaTypeData,
                                                      @RequestParam("teacherData")boolean teacherData,
                                                      @RequestParam("createUserData")boolean createUserData,
                                                      @RequestParam("qaAddData")boolean qaAddData,
                                                      @RequestParam("attendData")boolean attendData,
                                                      @RequestParam("tagData")boolean tagData,
                                                      @RequestParam("teacherPriceData") boolean teacherPriceData,
                                                      @RequestParam("replyUser") boolean replyUser){
        Pagination page = new Pagination();
        page.setCurrentPage(currentPage);
        page.setPageSize(pageSize);
        return questionBiz.queryQuestionListPage(page, condition, userId, qaTypeData, teacherData, createUserData, qaAddData, attendData, tagData, teacherPriceData,replyUser);
    }

    /**
     * 根据ID查询问题
     * @param questionId 问题ID
     * @return
     */
    @RequestMapping("/findQuestionById")
    public QaQuestion findQuestionById(@RequestParam("questionId")BigDecimal questionId,
                                       @RequestParam("qaTypeData")boolean qaTypeData,
                                       @RequestParam("teacherData")boolean teacherData,
                                       @RequestParam("createUserData")boolean createUserData,
                                       @RequestParam("qaAddData")boolean qaAddData,
                                       @RequestParam("attendData") boolean attendData,
                                       @RequestParam("tagData")boolean tagData,
                                       @RequestParam("teacherPriceData") boolean teacherPriceData){
        return questionBiz.findQuestionById(questionId, qaTypeData, teacherData, createUserData, qaAddData, attendData, tagData, teacherPriceData);
    }

    /**
     * 根据ID查询问题列表，并把列表转成Map
     * @param ids 问题ID串
     * @param qaTypeData 是否查询问答分类数据  true：是， false：否
     * @param teacherData 是否查询受问讲师数据  true：是， false：否
     * @param createUserData 是否查询提问人数据  true：是， false：否
     * @param qaAddData 是否查询追问数据  true：是， false：否
     * @return Map<BigDecimal,QaQuestion>
     */
    @RequestMapping("/findQuestionToMapByIds")
    public Map<BigDecimal,QaQuestion> findQuestionToMapByIds(@RequestParam("ids") String ids,boolean qaTypeData, boolean teacherData, boolean createUserData,
                                                             boolean qaAddData, boolean attendData, boolean tagData, boolean teacherPriceData){
        QuestionCondition condition = new QuestionCondition();
        condition.setIds(ids);
        condition.setQaTypeData(qaTypeData);
        condition.setTeacherData(teacherData);
        condition.setCreateUserData(createUserData);
        condition.setQaAddData(qaAddData);
        condition.setAttendData(attendData);
        condition.setTagData(tagData);
        condition.setTeacherPriceData(teacherPriceData);
        return questionBiz.findQuestionToMapByIds(condition);
    }

    /**
     * 根据ID查询问题列表，并把列表转成Map
     * @param condition 查询条件
     * @return Map<BigDecimal,QaQuestion>
     */
    @RequestMapping("/findQuestionToMap")
    public Map<BigDecimal,QaQuestion> findQuestionToMap(@RequestBody QuestionCondition condition){
        return questionBiz.findQuestionToMapByIds(condition);
    }

    /**
     * 根据ID查询要支付的问题列表，并把列表转成Map
     * @param ids 问题ID串
     * @param qaTypeData 是否查询问答分类数据  true：是， false：否
     * @param teacherData 是否查询受问讲师数据  true：是， false：否
     * @param createUserData 是否查询提问人数据  true：是， false：否
     * @param qaAddData 是否查询追问数据  true：是， false：否
     * @return Map<BigDecimal,QaQuestion>
     */
    @RequestMapping("/findPayQuestionMaps")
    public Map<BigDecimal,QaQuestion> findPayQuestionMaps(@RequestParam("ids") String ids,
                                                          @RequestParam("qaTypeData") boolean qaTypeData,
                                                          @RequestParam("teacherData") boolean teacherData,
                                                          @RequestParam("createUserData") boolean createUserData,
                                                          @RequestParam("qaAddData") boolean qaAddData,
                                                          @RequestParam("attendData") boolean attendData,
                                                          @RequestParam("tagData") boolean tagData,
                                                          @RequestParam("teacherPriceData") boolean teacherPriceData){
        return questionBiz.findPayQuestionMap(ids,qaTypeData, teacherData, createUserData, qaAddData, attendData, tagData, teacherPriceData);
    }

    /**
     * 根据ID查询问题
     * @param ids 问题ID串
     * @param qaTypeData 是否查询问答分类数据  true：是， false：否
     * @param teacherData 是否查询受问讲师数据  true：是， false：否
     * @param createUserData 是否查询提问人数据  true：是， false：否
     * @param qaAddData 是否查询追问数据  true：是， false：否
     * @return List<QaQuestion>
     */
    @RequestMapping("/findQuestionByIds")
    public List<QaQuestion> findQuestionByIds(String ids,boolean qaTypeData, boolean teacherData, boolean createUserData,
                                              boolean qaAddData, boolean attendData, boolean tagData, boolean teacherPriceData){
        QuestionCondition condition = new QuestionCondition();
        condition.setIds(ids);
        condition.setQaTypeData(qaTypeData);
        condition.setTeacherData(teacherData);
        condition.setCreateUserData(createUserData);
        condition.setQaAddData(qaAddData);
        condition.setAttendData(attendData);
        condition.setTagData(tagData);
        condition.setTeacherPriceData(teacherPriceData);
        return questionBiz.findQuestionByIds(condition);
    }

    /**
     * 修改问题状态
     * @param questionIds 问题ID串
     * @param status 状态：1.恢复，2.禁用，3.删除
     * @return Map<String, Object>
     */
    @RequestMapping("/updateQuestionStatus")
    public Map<String, Object> updateQuestionStatus(@RequestParam("questionIds")String questionIds,
                                                    @RequestParam("status")int status){
        if(StringUtils.isNotEmpty(questionIds) && StringUtils.isNotEmpty(questionIds.trim()) && status > 0) {
            //获取状态值与数据库不同的id串
            if (StringUtils.isNotEmpty(this.getStatusConflictIds(questionIds, status))) {
                if (status == 1) {
                    return ResultUtil.ERROR("所选问题正常，操作无效");
                }
                if (status == 2) {
                    return ResultUtil.ERROR("所选问题已禁用，操作无效");
                }
            }
            return questionBiz.updateQuestionStatus(questionIds, status);
        }
        return null;
    }

    /**
     * 获取与数据库状态值不同的id串
     *
     * @param questionIds
     * @param status
     * @return
     */
    private String getStatusConflictIds(String questionIds, int status){
        QuestionCondition condition = new QuestionCondition();
        condition.setIds(questionIds);
        condition.setStatus(status);
        List<QaQuestion> qaQuestionList = questionBiz.findQuestionByIds(condition);
        StringBuffer stringBuffer = new StringBuffer();
        if(ObjectUtils.isNotEmpty(qaQuestionList)){
            qaQuestionList.stream().forEach(v -> {
                Integer _status = v.getStatus();
                if(_status != status){
                    stringBuffer.append(v.getId()).append(",");
                }
            });
        }
        questionIds = StringUtils.subHeadTailString(stringBuffer.toString(),",");
        return questionIds;
    }

    /**
     * 后台保存问题答案
     * @param question
     * @return
     */
    @RequestMapping("/saveQuestionReply")
    public Map<String, Object> saveQuestionReply(@RequestBody QaQuestion question){
        if(!ObjectUtils.isNotEmpty(question)){
            return ResultUtil.ERROR("系统繁忙，请稍后重试");
        }
        if(!DataUtil.idIsNotNull(question.getId())){
            return ResultUtil.ERROR("问题ID为空，保存失败");
        }
        if(!StringUtils.isNotEmpty(question.getReplyContext()) || !StringUtils.isNotEmpty(question.getReplyContext().trim())){
            return ResultUtil.ERROR("回答内容不能为空");
        }
        if(!DataUtil.idIsNotNull(question.getReplyUserId())){
            return ResultUtil.ERROR("回答用户ID为空，保存失败");
        }
        if(!ObjectUtils.isNotEmpty(question.getCompleteStatus()) || (question.getCompleteStatus() !=1 && question.getCompleteStatus() !=2)){
            return ResultUtil.ERROR("完成状态错误，保存失败");
        }
        QuestionCondition condition = new QuestionCondition();
        condition.setIds(question.getId().toString());
        QaQuestion _question = questionBiz.findQuestionByIds(condition).get(0);
        _question.setReplyContext(question.getReplyContext().trim());
        _question.setCompleteStatus(question.getCompleteStatus());
        _question.setReplyUserId(question.getReplyUserId());
        _question.setReplyTime(new Date());
        questionBiz.addOrUpdateQuestion(_question);
        return ResultUtil.SUCCESS("保存成功");
    }

    /**
     * 前台查看问题详情方法
     * @param questionId 问题ID
     * @param userId 当前登录用户ID
     * @param qaTypeData 是否设置问答类型
     * @param userData 是否设置提问用户信息
     * @param teacherData 是否设置讲师信息
     * @param addData 是否设置追问信息
     * @param attendData 是否设置旁听用户信息
     * @param tagData 是否设置标签信息
     * @return
     */
    @RequestMapping("/findQuestionByIdForFront")
    public QaQuestion findQuestionByIdForFront(@RequestParam("questionId") BigDecimal questionId,
                                               @RequestParam(value = "userId", required = false, defaultValue = "0") BigDecimal userId,
                                               @RequestParam("qaTypeData") boolean qaTypeData,
                                               @RequestParam("userData") boolean userData,
                                               @RequestParam("teacherData") boolean teacherData,
                                               @RequestParam("addData") boolean addData,
                                               @RequestParam("attendData") boolean attendData,
                                               @RequestParam("tagData") boolean tagData,
                                               @RequestParam("teacherPriceData") boolean teacherPriceData){
        return questionBiz.findQuestionByIdForFront(questionId, userId, qaTypeData, userData, teacherData, addData, attendData, tagData, teacherPriceData);
    }

    /**
     * 查询我的问答列表
     * @param currentPage 页码
     * @param pageSize 每页显示条数
     * @param userId 用户ID
     * @param queryType 查询类型：1.我提问的-免费，2.我回答(评论)的，3.我提问的-付费，4.我围观的
     * @param qaTypeData 是否设置问答类型（true：是，false：否）
     * @param userData 是否设置提问用户信息（true：是，false：否）
     * @param teacherData 是否设置讲师信息（true：是，false：否）
     * @param addData 是否设置追问信息（true：是，false：否）
     * @param attendData 是否设置旁听用户信息（true：是，false：否）
     * @param tagData 是否设置标签信息（true：是，false：否）
     * @return
     */
    @RequestMapping("/queryMyQuestionList")
    public PageInfo<QaQuestion> queryMyQuestionList(@RequestParam(value = "currentPage", required = false, defaultValue = "1") int currentPage,
                                                    @RequestParam(value = "pageSize", required = false, defaultValue = "10") int pageSize,
                                                    @RequestParam("userId") BigDecimal userId,
                                                    @RequestParam("queryType") int queryType,
                                                    @RequestParam("qaTypeData") boolean qaTypeData,
                                                    @RequestParam("userData") boolean userData,
                                                    @RequestParam("teacherData") boolean teacherData,
                                                    @RequestParam("addData") boolean addData,
                                                    @RequestParam("attendData") boolean attendData,
                                                    @RequestParam("tagData") boolean tagData,
                                                    @RequestParam("teacherPriceData") boolean teacherPriceData){
        Pagination page = new Pagination();
        page.setCurrentPage(currentPage);
        page.setPageSize(pageSize);
        return questionBiz.queryMyQuestionList(page, userId, queryType, qaTypeData, userData, teacherData, addData, attendData, tagData, teacherPriceData);
    }

    /**
     * 校验用户是否可以免费提问
     * @param userId 用户ID
     * @return
     */
    @RequestMapping("/checkUserIsQuestion")
    public Map<String, Object> checkUserIsQuestion(@RequestParam("userId") BigDecimal userId){
        return questionBiz.checkUserIsQuestion(userId);
    }

    /**
     * 通过套餐ID查询课程列表
     * @param packageId
     * @return
     */
    @RequestMapping("/getCourseListByPackageId")
    public Map<String, Object> getCourseListByPackageId(@RequestParam("packageId") BigDecimal packageId){
        List<Course> courseList = questionBiz.getCourseListByPackageId(packageId);
        return ResultUtil.SUCCESS(courseList);
    }

    /**
     * 根据课程ID查询章节列表
     * @param courseId 课程ID
     * @return
     */
    @RequestMapping("/getCourseCatalogByCourseId")
    public Map<String, Object> getCourseCatalogByCourseId(@RequestParam("courseId") BigDecimal courseId){
        List<CourseCatalog> catalogList = questionBiz.getCourseCatalogByCourseId(courseId);
        return ResultUtil.SUCCESS(catalogList);
    }

    /**
     * 前台保存问题方法
     * @param question 问题数据
     * @return
     */
    @RequestMapping("/saveQuestion")
    public Map<String, Object> saveQuestion(@RequestBody QaQuestion question){
        Optional<Map<String, Object>> verify = verify(question);
        if(verify.isPresent()){
            return verify.get();
        }
        //查询系统配置是否允许自动退费
        TreeMap<String,String> attent = sysConfigService.getSysConfigContext(ConfigName.QAREFUND);
        String refundSwitch = attent.get("refundSwitch");
        if (refundSwitch.equals("ON")){
            question.setIsAllowedRefund(1);
        }else{
            question.setIsAllowedRefund(2);
        }
        questionBiz.addOrUpdateQuestion(question);
        // 提问题添加积分
        cusUserIntegralService.addUserIntegral(ActionKey.QUESTION, question.getUserId(), null, 0, 2);
        return ResultUtil.SUCCESS("提问成功",question);
    }

    /**
     * 提问时，校验数据
     * @param question 问题数据
     * @return
     */
    private Optional<Map<String, Object>> verify(QaQuestion question){
        if(ObjectUtils.isEmpty(question) || DataUtil.idIsNotNull(question.getId())){
            return Optional.of(ResultUtil.ERROR("系统繁忙，请稍后重试"));
        }
        if(question.getIsFree()!=1 && question.getIsFree()!=2){
            return Optional.of(ResultUtil.ERROR("系统繁忙，请稍后重试"));
        }
        if(!DataUtil.idIsNotNull(question.getUserId())){
            return Optional.of(ResultUtil.ERROR("提问用户ID为空，保存失败"));
        }
        if(StringUtils.isEmpty(question.getContext()) || "".equals(question.getContext().trim())){
            return Optional.of(ResultUtil.ERROR("问题内容不能为空"));
        }
        if(question.getContext().trim().length() >200){
            return Optional.of(ResultUtil.ERROR("问题字数不能超过200"));
        }
        if(!DataUtil.idIsNotNull(question.getTypeId())){
            return Optional.of(ResultUtil.ERROR("请选择问答分类"));
        }
        if(ObjectUtils.isEmpty(question.getPrivacy()) || (question.getPrivacy().intValue() !=1 && question.getPrivacy().intValue()!=2)){
            return Optional.of(ResultUtil.ERROR("是否隐私提问状态错误"));
        }
        if(question.getIsFree() == 2){
            if(!DataUtil.idIsNotNull(question.getTeacherId())){
                return Optional.of(ResultUtil.ERROR("讲师ID为空，保存失败"));
            }
        }
        return Optional.empty();
    }

    /**
     * 查询问答总数量数据
     * @return QaSumCount
     */
    @RequestMapping("/queryQaSumCount")
    public QaSumCount queryQaSumCount(){
        return questionBiz.queryQaSumCount();
    }



    /**
     * 根据用户id查询用户提问列表
     * @param userId 用户id
     * @return
     */
    @RequestMapping("/findQaQuestionByUserId")
    List<QaQuestion> findQaQuestionByUserId(@RequestParam("userId") BigDecimal userId){
        return questionBiz.find(" userId= " + userId + " AND TO_DAYS(createTime) =TO_DAYS(NOW()) ", null, null);
    }

}



